import React, { FC, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import { TextareaItem, Button } from 'antd-mobile-v2';
import styles from './index.module.less';
import { createForm } from '@/components/rc-form';
import { IApprovalActionReq } from '@/services/approval';
import { ConnectProps } from 'typings/connect';
import FormRender from '@/plugins/form/form-render';
import H5Components from '@/plugins/form/form-components';
import { IApprovalItem } from '../../type';
import {
  parseValueForDetail,
  parseFormData,
  parseValue,
  filterDataToBackEnd
} from '@/plugins/form/form-render/utils/detail-parser';
import { IGaeaInstance } from '@/plugins/form/types';
import { AppPopBack, AppRefresh, AppToast } from '@/utils/app-func';
import { Actions, TabIds, ActionsText } from '../../constants';
import emptyImg from '@/assets/approval/dafult-404.png';
import { SUCCESS_CODE } from '@/services/constant';

export interface IActionModal extends ConnectProps {
  onCancel?: (needRefresh?: boolean) => void;
  loading?: boolean;
  onRefresh?: () => void;
  onRefreshStatus?: () => void;
  form?: any;
  location: any;
}
// 审批业务-同意/拒绝
const ActionModal: FC<IActionModal> = (props) => {
  const [currentTask, setCurrentTask] = useState<IApprovalItem>();
  const [formValuesG, setFormValues] = useState<{
    [index: string]: any;
  }>();
  const [editableForm, setEditableForm] = useState<{
    [index: string]: IGaeaInstance;
  }>();
  const [otherHandled, setOtherHandled] = useState(false);
  const [isAction, setIsAction] = useState(false);
  const [handlerComment, setHandlerComment] = useState('');
  // let handlerComment = '';

  useEffect(() => {
    pageInit();
  }, []);

  const pageInit = () => {
    if (
      props.location.query?.procNo &&
      props.location.query?.taskDefKey &&
      props.dispatch &&
      props.location.query?.tabId == TabIds.ToApproval
    ) {
      props
        .dispatch({
          type: 'capproval/getTaskHandler',
          payload: {
            procNo: props.location.query?.procNo,
            defKey: props.location.query?.taskDefKey
          }
        })
        .then(async (res?: any) => {
          // procStatus流程状态( 1审批中 2已完成  3已拒绝 4已撤销)
          // isHandled( 1本人处理过  0未处理过 )
          // isCanHandled( 1能被处理 0不能被处理 )
          // if (res.data?.isHandled == 1 && res.data?.isCanHandled != 1) {
          //    该申请已被自己处理
          //   getDetails();
          // }
          // else
          if (res.data?.isCanHandled == 0 && res.data?.isHandled == 0) {
            document.title = '审批详情';
            //该申请已被他人处理！
            setOtherHandled(true);
          } else {
            setOtherHandled(false);
            getDetails();
          }
        });
    } else {
      getDetails();
    }
  };

  const getDetails = () => {
    const tabId = props.location?.query.tabId;
    const type =
      tabId === TabIds.MyApply
        ? 'capproval/getProcDetail'
        : 'capproval/getTaskDetail';
    const id = props.location?.query.recordId;
    const payload =
      tabId === TabIds.MyApply ? { procRecordId: id } : { taskRecordId: id };
    if (!id) return;
    props.dispatch &&
      props
        .dispatch({
          type: type,
          payload: payload
        })
        .then((res: any) => {
          let name;
          if (res.data?.procName.lastIndexOf('申请') === -1) {
            name = res.data?.procName + '申请';
          } else {
            name = res.data?.procName;
          }
          document.title = name ? name : '审批详情';
          setFormParse(res.data);
          setCurrentTask(res.data);
        });
  };

  const setFormParse = (task: any) => {
    // 合并值和json
    const tabId = props.location.query.tabId;
    let formParsed: { [index: string]: any } = parseFormData(
      task?.formData.formModelData,
      tabId === TabIds.MyApply ? 'all' : task.taskDefKey,
      false
    );
    const formValuesS = parseValue(task?.formData.formValues);
    formParsed = parseValueForDetail(formParsed, formValuesS);
    const editableFormParsed: any = {};
    Object.keys(formParsed).forEach((key: string) => {
      // 添加可编辑的元素
      const permission = formParsed[key].data.props.permission;
      if (permission === 'editable') {
        editableFormParsed[key] = formParsed[key];
      }
      // 递归遍历容器的子元素,若有可编辑的元素,则添加容器
      if (formParsed[key].childs.length > 0) {
        const isEditable = filterData(
          formParsed[key].childs,
          formParsed,
          'permission'
        );
        if (isEditable) {
          editableFormParsed[key] = formParsed[key];
        }
      }
      // 添加可编辑时间区间中的每一项
      const parentInstanceKey = formParsed[key].data.props.parentInstanceKey;
      if (parentInstanceKey?.indexOf('rangepicker') != -1 && formParsed[parentInstanceKey]?.data?.props?.permission === 'editable') {
        editableFormParsed[key] = formParsed[key];
      }
    });

    // console.log('formParsed-------',formParsed);
    // console.log('editableFormParsed-------',editableFormParsed);
    setEditableForm(editableFormParsed);
    setFormValues(formValuesS);
  };

  const filterData = (
    data: any[],
    formObj: { [index: string]: any },
    keyword?: string
  ) => {
    if (!keyword || !data) {
      return data;
    }
    const children: any[] = doFilter(JSON.parse(JSON.stringify(data)), formObj);
    const isEditable = children.some(
      (item: any) => item.data.props[keyword] === 'editable'
    );
    return isEditable;
  };
  const doFilter = (
    arr: string[] | undefined,
    formObj: { [index: string]: any }
  ) => {
    if (!arr) {
      return [];
    }
    let result: any[] = [];
    for (let i = 0; i < arr.length; i++) {
      const arrItem = formObj[arr[i]];
      result.push(formObj[arr[i]]);
      if (arrItem.childs.length > 0) {
        const children: any[] = doFilter(arrItem.childs, formObj);
        result = [...result, ...children];
      }
    }
    return result;
  };

  const handleOk = async () => {
    const result = await props.form.getFieldsValue();
    console.log('handleOk----result', result);
    const required = props.location?.query.action === ActionsText.Reject ? true : false;
    const requiredTitle = props.location?.query.action === ActionsText.Reject ? '拒绝原因' : '审批意见';
    if (required && !handlerComment) {
      AppToast({ type: 2, message: `请输入${requiredTitle}` });
      console.log(`请输入${requiredTitle}`);
      return;
    }
    const formValues1 = parseValue(currentTask?.formData.formValues);
    const formParsed1 = parseFormData(currentTask?.formData.formModelData);
    const data = {
      // 这里加上前面步骤填写的参数
      formValues: JSON.stringify(
        filterDataToBackEnd(formParsed1, { ...(formValues1 || {}), ...result })
      ),
      formModelData: currentTask?.formData.formModelData
    };

    // 同意的时候取到error的第一个进行提示  取不到明细里正确的必填信息 todo
    await props.form.validateFields(
      (err: any) => {
        console.log('err', err);
        if (err) {
          console.log('Object.keys(err)', Object.keys(err));
          const firstKey = Object.keys(err)[0];
          const errMessage = err[firstKey].errors?.[0].message;
          console.log('errMessage', errMessage);
          errMessage && AppToast({ type: 2, message: errMessage });
        }
      }
    );
    const actions =
      props.location?.query.action === ActionsText.Agree
        ? Actions.Agree
        : props.location?.query.action === ActionsText.Reject
          ? Actions.Reject
          : '';
    const params: IApprovalActionReq = {
      forms: data,
      action: actions,
      handlerComment: handlerComment, // 处理意见  result.handlerComment
      taskRecordId: currentTask?.taskRecordId
    };
    // console.log('ok--params :', params);
    if (!isAction) {
      setIsAction(true);
      if (props.dispatch) {
        props
          .dispatch({
            type: 'capproval/doTask',
            payload: params
          })
          .then((res?: any) => {
            setIsAction(false);
            if (res && res.status == SUCCESS_CODE) {
              const type = props.location.query.type || '';
              AppToast({ type: 1, message: res.message });
              if (type === 'fromDetail') {
                props.history?.goBack(); //返回审批详情
                AppRefresh(); //刷新app列表数据
              } else {
                AppPopBack(); //返回审批列表
                AppRefresh(); //刷新app列表数据
              }
            }
          })
          .catch((err: any) => {
            setIsAction(false);
            console.log('err', err);
          });
      }
    }
  };

  const onChange = async (val: any) => {
    const value = val;
    // eslint-disable-next-line no-misleading-character-class
    const reg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\\A9|\\AE]\u3030|\uA9|\uAE|\u3030/ig;
    const form = props.form;
    if (!form) {
      return;
    }
    console.log('onchange', value?.replace(reg, ''));
    setHandlerComment(value?.replace(reg, ''));
    // // 只能输入中文，英文，数字，标点符号
  };

  const action = props.location.query.action;
  const confirmText = action === ActionsText.Reject ? '拒绝' : '同意';
  const textTitle = action === ActionsText.Reject ? '拒绝原因' : '审批意见';

  if (otherHandled)
    return (
      <div className={styles.emptyWrap}>
        <img
          src={emptyImg}
          className={styles.emptyImg}
          alt="该申请已被他人处理"
        />
        <span className={styles.emptyText}>该申请已被他人处理</span>
      </div>
    );

  props.form.getFieldError('handlerComment') || [];
  return (
    <div className={styles.actionWrapper}>
      {editableForm && Object.keys(editableForm).length > 0 && action === ActionsText.Agree ? (
        <div className={styles.formWrap}>
          <FormRender
            renderMode="actionEditable"
            form={props.form}
            key={currentTask?.taskRecordId}
            componentClasses={H5Components}
            value={editableForm}
            formValues={formValuesG}
          />
        </div>
      ) : null}
      <TextareaItem
        className={styles.actionTextarea}
        title={textTitle}
        placeholder={`请输入${textTitle}`}
        autoHeight
        rows={3}
        maxLength={100}
        {...props}
        value={handlerComment}
        onChange={onChange}
      />
      <Button type="primary" className={styles.confirmBtn} loading={isAction} onClick={handleOk}>
        {confirmText}
      </Button>
    </div>
  );
};
const ActionModalWrapper = createForm()(ActionModal);
export default connect()(ActionModalWrapper);
